package com.engine.api.dckj.mh.web;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.engine.api.dckj.mh.service.UserLocationService;
import com.engine.api.dckj.mh.service.impl.UserLocationServiceImpl;
import com.engine.api.dckj.mh.entity.UserLocationInfo;
import com.wbi.util.ParamUtil;
import com.wbi.util.Util;
import weaver.conn.RecordSet;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;
import weaver.hrm.company.DepartmentComInfo;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.*;
import java.util.logging.Logger;
import java.util.stream.Collectors;

public class UserLocationAction {
    private static Logger logger = Logger.getLogger(UserLocationAction.class.getName());
    @POST
    @Path("/getUserListByDepartment")
    // 获取部门下所有人员id，name
    public String getUserListByDepartment(@Context HttpServletRequest request, @Context HttpServletResponse response){
        Map<String,Object> stringObjectMap = ParamUtil.request2Map(request);
        Object deptIdObj = stringObjectMap.get("deptId")==null?"":stringObjectMap.get("deptId");

        logger.info("传入的参数deptId："+ deptIdObj);
        RecordSet recordSet = new RecordSet();
        List<String> childList = new ArrayList<>();
        List<User> list = new ArrayList<>();
        if(!"".equals(deptIdObj)){// 传部门id
            try {
                childList.add(DepartmentComInfo.getAllChildDepartId(deptIdObj.toString(), deptIdObj.toString()));
            } catch (Exception e) {
                e.printStackTrace();
            }
            String join = String.join(StrUtil.COMMA, childList);
            return getUsers(recordSet, list, join);
        }else {// 不传部门id
            // 获取登录用户  -- 查询为user为null
            User user = HrmUserVarify.getUser(request, response);
            // 登录用户部门id
            int userDepartment = getUserDepartment(user);
            try {
                childList.add(DepartmentComInfo.getAllChildDepartId(Integer.toString(userDepartment), Integer.toString(userDepartment)));
            } catch (Exception e) {
                e.printStackTrace();
            }
            String join = String.join(StrUtil.COMMA, childList);
            return getUsers(recordSet, list, join);
        }
    }

    private String getUsers(RecordSet recordSet, List<User> list, String join) {
        JSONObject jsonObject = new JSONObject();
        String sql = "select id,lastname from hrmresource where departmentid in ("+join+")   and status < 3";
        logger.info("查询部门下所有用户sql："+ sql);
        recordSet.executeQuery(sql);
        while (recordSet.next()) {
            String id = Util.null2String(recordSet.getString("id"));
            String lastname = Util.null2String(recordSet.getString("lastname"));
            User user1 = new User();
            user1.setUid(Integer.parseInt(id));
            user1.setLastname(lastname);
            list.add(user1);
        }
        jsonObject.put("userList", list);
        return jsonObject.toJSONString();
    }

    @POST
    @Path("/getUserLocationByUserAndDateRange")
    // 通过条件获取地图列表
    public String getUserLocationByUserAndDateRange(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        UserLocationService userLocationService = new UserLocationServiceImpl();
        Map<String,Object> stringObjectMap = ParamUtil.request2Map(request);
        Object startTimeObj = stringObjectMap.get("startTime")==null?"":stringObjectMap.get("startTime");
        Object endTimeObj = stringObjectMap.get("endTime")==null?"":stringObjectMap.get("endTime");
        Object userIdObj = stringObjectMap.get("userId")==null?"":stringObjectMap.get("userId");
        JSONObject jsonObject = new JSONObject();
        try {
            if ("".equals(userIdObj) && "".equals(startTimeObj) && "".equals(endTimeObj)) {
                RecordSet recordSet = new RecordSet();
                // 获取登录用户
                User user = HrmUserVarify.getUser(request, response);
                // 登录用户部门id
                int userDepartment = getUserDepartment(user);
                List<String> childList = new ArrayList<>();
                try {
                    childList.add(DepartmentComInfo.getAllChildDepartId(Integer.toString(userDepartment), Integer.toString(userDepartment)));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                String join = String.join(StrUtil.COMMA, childList);
                String sql = "select id from hrmresource where departmentid in(" + join + ") and status < 3";
                recordSet.executeQuery(sql);
                ArrayList<String> list = new ArrayList<>();
                while (recordSet.next()) {
                    String id = Util.null2String(recordSet.getString("id"));
                    list.add(id);
                }
                // 通过id列表查询对应的人员最新的坐标点列表
                List<UserLocationInfo> userLocationByUserIdList = userLocationService.getUserLocationByUserIdList(list);
                jsonObject.put("userLocationByUserIdList", userLocationByUserIdList);
                return jsonObject.toJSONString();
            }
            if(!"".equals(userIdObj)  &&  "".equals(startTimeObj) &&  "".equals(endTimeObj)) {
                String id = userIdObj.toString();
                List<UserLocationInfo> userLocationByUserIdList = userLocationService.getUserLocationByUserAndDateRange(id, null, null);
                jsonObject.put("userLocationByUserIdList", userLocationByUserIdList);
                return jsonObject.toJSONString();
            }
            if (!"".equals(userIdObj) && !"".equals(startTimeObj)  && !"".equals(endTimeObj)) {
                String id = userIdObj.toString();
                String startTime = startTimeObj.toString();
                String endTime = endTimeObj.toString();
                List<UserLocationInfo> userLocationByUserIdList = userLocationService.getUserLocationByUserAndDateRange(id, startTime, endTime);
                jsonObject.put("userLocationByUserIdList", userLocationByUserIdList);
                return jsonObject.toJSONString();
            }
            if ("".equals(userIdObj)  && !"".equals(startTimeObj)  && !"".equals(endTimeObj)) {
                RecordSet recordSet = new RecordSet();
                // 获取登录用户
                User user = HrmUserVarify.getUser(request, response);
                // 登录用户部门id
                int userDepartment = getUserDepartment(user);
                List<String> childList = new ArrayList<>();
                try {
                    childList.add(DepartmentComInfo.getAllChildDepartId(Integer.toString(userDepartment), Integer.toString(userDepartment)));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                String join = String.join(StrUtil.COMMA, childList);
                String sql = "select id from hrmresource where departmentid in (" + join + ") and status < 3";
                recordSet.executeQuery(sql);
                ArrayList<Integer> list = new ArrayList<>();
                while (recordSet.next()) {
                    String id = Util.null2String(recordSet.getString("id"));
                    list.add(Integer.parseInt(id));
                }
                String id = list.stream().filter(Objects::nonNull).distinct()
                        .map(String::valueOf)
                        .collect(Collectors.joining(","));
                String startTime = startTimeObj.toString();
                String endTime = endTimeObj.toString();
                List<UserLocationInfo> userLocationByUserIdList = userLocationService.getUserLocationByUserAndDateRange(id, startTime, endTime);
                jsonObject.put("userLocationByUserIdList", userLocationByUserIdList);
                return jsonObject.toJSONString();
            }
            if (!"".equals(userIdObj) && "".equals(startTimeObj)) {
                String id = userIdObj.toString();
                String endTime = endTimeObj.toString();
                List<UserLocationInfo> userLocationByUserIdList = userLocationService.getUserLocationByUserAndDateRange(id, null, endTime);
                jsonObject.put("userLocationByUserIdList", userLocationByUserIdList);
                return jsonObject.toJSONString();
            }
            if (!"".equals(userIdObj) ) {
                String id = userIdObj.toString();
                String startTime = startTimeObj.toString();
                List<UserLocationInfo> userLocationByUserIdList = userLocationService.getUserLocationByUserAndDateRange(id, startTime, null);
                jsonObject.put("userLocationByUserIdList", userLocationByUserIdList);
                return jsonObject.toJSONString();
            }

        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
        return null;
    }

    private static int getUserDepartment(User user) {
        if(user == null){
            return 0;
        }
        return user.getUserDepartment();
    }
}
